import React, { Component } from 'react'
import OrderItem from '../OrderItem'

export class OrderList extends Component {
  constructor(props) {
    super(props)

    this.state = {
      data: []
    }
  }

  componentDidMount = () => {
    fetch('/mock/orders.json').then(res => {
      if (res.ok) {
        res.json().then(data => {
          this.setState({ data })
        })
      }
    })
  }

  render() {
    return (
      <div>
        {this.state.data.map(item => {
          return (
            <OrderItem onSubmit={this.handleSubmit} data={item} key={item.id} id={item.id} />
          )
        })}
      </div>
    )
  }

  handleSubmit = (id, comment, stars) => {
    /**
    |--------------------------------------------------
    | 正式开发中应该调用接口保存数据成功后，在回调函数中进行页面数据更新。
    |--------------------------------------------------
    */
    // fetch('/saveComment').then(() => {})

    const newData = this.state.data.map(item => {
      return item.id === id
        ? {
            ...item,
            comment: comment,
            stars: stars,
            ifCommented: true
          }
        : item
    })

    this.setState({
      data: newData
    })
  }
}

export default OrderList
